<template>
  <div class='mobile-phone-wrapper'>
    <div class='preview-box-wrapper'>
      <!-- 关闭预览 -->
      <div class='preview-close iconfont' @click='closePreview'>&#xe623;</div>
      <!-- 二维码 -->
      <div class='preview-qr-wrapper'>
        <div class='qr-header'>
          <span class='header-icon survey-sprite-bg'></span>
          <span class='header-text'>扫码预览</span>
        </div>
        <div class='qr-body'>
          <qr-code
            class='qr-body-code'
            :url='previewMobileUrl'
            :width='100'
            :height='100'
            colorFront='#333'>
          </qr-code>
        </div>
        <div class='qr-footer'>仅供预览 请勿传播</div>
      </div>
      <!-- 预览手机 -->
      <div class='preview-box'>
        <div class='box-body'
              :class='{
                hideCover: !displayCover || (!coverSetting.bgImg && !coverSetting.bgColor)
              }'>
          <!-- 问卷封面预览， 如果设置了背景图片，或背景色 -->
          <div class='cover-wrapper'
              v-if='coverSetting.bgImg || coverSetting.bgColor'
              :class='{
                isSlide: coverSetting.startWay === 2, // 控制封面是否滑动显隐
                useBgImg: coverSetting.bgType === 1,
                useBgColor: coverSetting.bgType === 2
              }'
              :style='{
                maxHeight: `${coverHeight}px`,
                backgroundImage: `url(${coverSetting.bgImg})`,
                backgroundColor: coverSetting.bgColor
              }'>
            <div class='cover-title'
                  v-show='coverSetting.showTitle && displaySetting.showTitle'
                  v-html='survey.richTextTitle'
                  :class='{
                    top: coverSetting.titleLocation === "top",
                    center: coverSetting.titleLocation === "center",
                    bottom: coverSetting.titleLocation === "bottom"
                  }'
                  :style='{
                    color: coverSetting.titleFontColor,
                    fontSize: coverSetting.titleFontSize + "px"
                  }'>
            </div>
            <div class='cover-btn'
                  v-show='coverSetting.startWay === 1'
                  :style='{
                    color: coverSetting.buttonFontColor,
                    backgroundColor: coverSetting.buttonBaseColor
                  }'
                  @click='slideUpCover()'>
              {{coverSetting.buttonText}}
            </div>
            <div class='cover-slide'
                  v-show='coverSetting.startWay === 2'>
              <span class='slide-text' @click='slideUpCover'>上滑开始</span>
              <span class='slide-icon' @click='slideUpCover'></span>
            </div>
          </div>
          <!-- 问卷内容预览 -->
          <div class='survey-wrapper'
               v-show='!loading'
              :class='{
                showBg: (bgSetting.bgType === 1 && bgSetting.bgImg) || (bgSetting.bgType === 2 && bgSetting.bgColor),
                useBgImg: bgSetting.bgType === 1,
                useBgColor: bgSetting.bgType === 2
              }'
              :style='{
                backgroundColor: bgSetting.bgColor,
                backgroundImage: `url(${bgSetting.bgImg})`
              }'>
            <div class='survey-page-bg'
                  :style='{opacity: bgSetting.bgOpacity / 100}'></div>
            <div class='survey-page'>
              <!-- 页眉 -->
              <div class='survey-header'
                    v-show='headerSetting.showHeader &&
                           (headerSetting.headerText || headerSetting.headerImg) &&
                           (!survey.pagingMode || (survey.pagingMode && currQaIndex === 0))'>
                <!-- 文字 -->
                <div class='header-text'
                      v-show='headerSetting.headerType === 1 && headerSetting.headerText'
                      v-html='headerSetting.headerText'
                      :style='{backgroundColor: headerSetting.headerBgColor}'>
                </div>
                <!-- 图片 -->
                <img class='header-img'
                      v-show='headerSetting.headerType === 2 && headerSetting.headerImg'
                      :src='headerSetting.headerImg'>
              </div>
              <!-- 标题 -->
              <div class='survey-cover'
                  v-show='survey.richTextTitle &&
                       !coverSetting.bgImg &&
                       !coverSetting.bgColor &&
                       (!survey.pagingMode || (survey.pagingMode && currQaIndex === 0))'
                  v-html='survey.richTextTitle'>
              </div>
              <!-- 欢迎语 -->
              <div class='survey-accessText'
                  v-show='survey.accessText &&
                          displaySetting.showWelcome &&
                          (!survey.pagingMode || (survey.pagingMode && currQaIndex === 0))'
                  v-html='survey.accessText'>
              </div>
              <!-- 题目列表 -->
              <ul class='survey-question'>
                <li class='question-item'
                    v-for='(qa, index) of qaList'
                    :key='"qa" + index'
                    v-show='!survey.pagingMode || (survey.pagingMode && currQaIndex === index)'>
                  <!-- 题目标题 -->
                  <div class='qa-title'>
                    <div class='title-content' v-html='qa.topic'></div>
                  </div>
                  <!-- 单选题 -->
                  <mobile-singleSelect
                    v-if='qa.type === "RADIO"'
                    :question='qa'>
                  </mobile-singleSelect>
                  <!-- 多选题 -->
                  <mobile-multiSelect
                    v-if='qa.type === "MULTIPLE"'
                    :question='qa'>
                  </mobile-multiSelect>
                  <!-- 图片选择题 -->
                  <mobile-picSelect
                    v-if='qa.type === "PIC_CHOOSE"'
                    :question='qa'>
                  </mobile-picSelect>
                  <!-- 图片投票题 -->
                  <mobile-picVote
                    v-if='qa.type === "PIC_VOTE"'
                    :question='qa'>
                  </mobile-picVote>
                  <!-- 文字投票题 -->
                  <mobile-textVote
                    v-if='qa.type === "TEXT_VOTE"'
                    :question='qa'>
                  </mobile-textVote>
                  <!-- 量表题 -->
                  <mobile-scaling
                    v-if='qa.type === "SCALE"'
                    :question='qa'>
                  </mobile-scaling>
                  <!-- 单项填空题 -->
                  <mobile-singleFill
                    v-if='qa.type === "FILLS"'
                    :question='qa'>
                  </mobile-singleFill>
                  <!-- 多项填空题 -->
                  <mobile-multiFill
                    v-if='qa.type === "MULTITERM_FILLS"'
                    :question='qa'>
                  </mobile-multiFill>
                  <!-- 评价题 -->
                  <mobile-rating
                    v-if='qa.type === "EVALUATION"'
                    :question='qa'>
                  </mobile-rating>
                  <!-- 打分题 -->
                  <mobile-score
                    v-if='qa.type === "GRADE"'
                    :question='qa'>
                  </mobile-score>
                </li>
              </ul>
              <!-- 按钮 -->
              <div class='survey-btn-list'>
                <div class='btn-item prev'
                     v-show='survey.pagingMode && currQaIndex > 0'
                    :style='{
                      color: buttonSetting.globalButtonColor,
                      borderColor: buttonSetting.globalButtonColor
                    }'
                    @click='showQa(-1)'>
                  上一页
                </div>
                <div class='btn-item next'
                     v-show='survey.pagingMode && currQaIndex < qaList.length - 1'
                    :style='{
                      backgroundColor: buttonSetting.globalButtonColor,
                      borderColor: buttonSetting.globalButtonColor
                    }'
                    @click='showQa(1)'>
                  下一页
                </div>
                <div class='btn-item next'
                     v-show='(survey.pagingMode && currQaIndex >= qaList.length - 1) ||
                           !survey.pagingMode'
                     :style='{
                      backgroundColor: buttonSetting.globalButtonColor,
                      borderColor: buttonSetting.globalButtonColor
                     }'>
                  {{buttonSetting.submitButtonText}}
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class='box-home'>
          <span class='home-icon'></span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import qrCode from 'public/qr-code'
import mobileSingleSelect from './mobile-singleSelect'
import mobileMultiSelect from './mobile-multiSelect'
import mobilePicSelect from './mobile-picSelect'
import mobilePicVote from './mobile-picVote'
import mobileTextVote from './mobile-textVote'
import mobileScaling from './mobile-scaling'
import mobileSingleFill from './mobile-singleFill'
import mobileMultiFill from './mobile-multiFill'
import mobileRating from './mobile-rating'
import mobileScore from './mobile-score'
export default {
  name: 'mobilePhone',
  data () {
    return {
      loading: true,
      setting: {
        coverSetting: '',
        headerSetting: '',
        bgSetting: '',
        buttonSetting: '',
        displaySetting: ''
      },
      // 封面设置
      coverSetting: {
        bgType: 1, // 1 为封面背景使用图片  2 为封面背景使用颜色
        bgImg: '', // 封面背景图
        bgColor: '', // 封面背景色
        showTitle: true, // 是否显示标题
        titleLocation: 'top', // 标题显示位置
        titleFontSize: 24, // 标题字体大小
        titleFontColor: '#000000', // 标题颜色
        startWay: 1, // 开始方式 （点击按钮/向上滑动）
        buttonBaseColor: '#2672ff', // 按钮底色
        buttonFontColor: '#ffffff', // 按钮字体颜色
        buttonText: '立即开始' // 按钮字体内容
      },
      // 页眉设置
      headerSetting: {
        showHeader: true,
        headerType: 1, // 1 为使用文字  2 为使用图片
        headerText: '',
        headerBgColor: '#eff4fe',
        headerImg: ''
      },
      // 背景设置
      bgSetting: {
        bgType: 1,
        bgColor: '',
        bgImg: '',
        bgOpacity: 100
      },
      // 按钮设置
      buttonSetting: {
        globalButtonColor: '#2672ff',
        startButtonText: '立即开始',
        submitButtonText: '提交'
      },
      // 显示设置
      displaySetting: {
        showQuestionNum: true,
        showTitle: true,
        showWelcome: true
      },
      survey: {
        surveyId: '1',
        title: '', // 问卷标题
        richTextTitle: '', // 展示的问卷标题
        accessText: '', // 问卷开始语
        closeText: '', // 问卷正常结束语
        advanceText: '', // 问卷提前结束语
        pagingMode: false // 为true时，一页展示一题
      },
      qaList: [],
      displayCover: true,
      coverHeight: 446,
      previewMobileUrl: 'https://www.baidu.com',
      // 分页相关
      currQaIndex: 0
    }
  },
  components: {
    qrCode,
    mobileSingleSelect,
    mobileMultiSelect,
    mobilePicSelect,
    mobilePicVote,
    mobileTextVote,
    mobileScaling,
    mobileSingleFill,
    mobileMultiFill,
    mobileRating,
    mobileScore
  },
  props: {
    surveyId: {
      type: String,
      default: ''
    }
  },
  methods: {
    showQa (step) {
      this.currQaIndex += step
    },
    closePreview () {
      this.$emit('close')
    },
    // 上滑隐藏封面页，展示题目页
    slideUpCover () {
      this.displayCover = false
      this.coverHeight = 0
    },
    // 获取问卷基本信息
    getSurveyDetail () {
      let url = `${this.SERVICE_UPGRADE_SURVEY}/${this.surveyId}`
      this.get(url).then(res => {
        if (res.data.code === 200 && res.data.data) {
          this.survey = res.data.data
        }
      })
    },
    // 获取设置接口
    getSetting () {
      let url = `${this.SERVICE_UPGRADE_SURVEY}/setting/${this.surveyId}`
      this.get(url).then(res => {
        if (res.data.code === 200 && res.data.data) {
          // console.log('res.data: ', res.data.data)
          let data = res.data.data
          for (let key of Object.keys(this.setting)) {
            if (data[key]) {
              this[key] = data[key]
            }
          }
        }
        this.getQaList()
      })
    },
    // 获取问卷的信息和题目列表
    getQaList () {
      let url = `${this.SERVICE_UPGRADE_SURVEY}/questions/${this.surveyId}`
      this.get(url).then(res => {
        if (res.data.code === 200 && res.data.data) {
          let qaList = res.data.data
          // 给所有选项添加isSelected字段
          qaList.forEach(qa => {
            qa.optionList.forEach(option => {
              option.isSelected = false
            })
            // 如果是打分题，需要初始化每个打分选项的数据
            if (qa.type === 'GRADE') {
              qa.optionList.forEach(option => {
                option.selectedScore = -1
                option.activeIndex = -1
              })
            }
          })
          this.qaList = qaList
          this.updateQaOrdinal()
          this.loading = false
        } else {
          this.loading = false
        }
      })
    },
    // 根据主题设置是否显示题目序号，题目的顺序，序号显隐情况，更新题目的序号
    updateQaOrdinal () {
      let ordinal = 1
      this.qaList.forEach(qa => {
        if (this.displaySetting.showQuestionNum) {
          if (qa.showNumber) {
            qa.ordinal = ordinal
            ordinal++
          } else {
            qa.ordinal = ''
          }
        } else {
          qa.ordinal = ''
        }
        this.updateTopicOrdinal(qa)
      })
    },
    // 根据ordinal字段，再题目的标题中显隐序号
    updateTopicOrdinal (qa) {
      let topic = qa.topic
      let ordinal = qa.ordinal
      let startLabel = '<span class="ordinal">'
      let endLabel = '</span>'
      let startIndex = topic.indexOf(startLabel)
      // 如果需要隐藏序号
      if (!ordinal) {
        // 如果原本有序号
        if (startIndex !== -1) {
          let endIndex = topic.indexOf(endLabel, startIndex)
          let text1 = topic.slice(0, startIndex)
          let text2 = topic.slice(endIndex + endLabel.length)
          qa.topic = text1 + text2
        }
      // 如果需要显示序号
      } else {
        // 如果原本有序号
        if (startIndex !== -1) {
          let endIndex = topic.indexOf('</span>', startIndex)
          let text1 = topic.slice(0, startIndex + startLabel.length)
          let text2 = topic.slice(endIndex)
          qa.topic = text1 + qa.ordinal + '.' + text2
        // 如果原本没有序号, 在第一个文本元素中插入序号
        } else {
          let matchResult = topic.match(/>[^<]/)
          let insertIndex = 0
          if (matchResult && matchResult.index) {
            insertIndex = matchResult.index + 1
          }
          let text1 = topic.slice(0, insertIndex)
          let text2 = topic.slice(insertIndex)
          let insertText = startLabel + qa.ordinal + '.' + endLabel
          qa.topic = text1 + insertText + text2
        }
      }
    },
    init () {
      this.getSurveyDetail()
      this.getSetting()
    }
  },
  created () {
    this.init()
  }
}
</script>

<style lang="stylus" scoped>
.mobile-phone-wrapper
  position fixed
  top 0
  left 0
  right 0
  bottom 0
  z-index 1000
  background rgba(47,52,79,0.67)
  .preview-box-wrapper
    position absolute
    left 0
    right 0
    top 0
    bottom 0
    margin auto
    width 307px
    height 587px
    background url('~assets/img/phone-box.png') no-repeat 0 0 / 100% 100%
    .preview-close
      position: absolute;
      right: -40px;
      top: 10px;
      padding: 6px;
      text-align center
      font-size: 14px;
      border-radius: 50%
      color rgba(255,255,255,0.7)
      cursor pointer
    .preview-qr-wrapper
      position absolute
      left -150px
      top 60px
      background: #fff;
      // box-shadow: 0 2px 4px 1px rgba(0,0,0,.05);
      border-radius: 8px;
      width: 134px;
      .qr-header
        height 24px
        padding 18px 0
        display flex
        align-items center
        justify-content center
        .header-icon
          width 24px
          height 24px
          display block
          margin-right 10px
          background-position -360px -72px
        .header-text
          font-size: 14px;
          color: #484848;
      .qr-body
        width 100px
        height 100px
        margin auto
      .qr-footer
        padding 12px 0 20px
        font-size: 12px;
        color: #707070;
        line-height: 12px;
        text-align center
    .preview-box
      position: absolute;
      left: 19px;
      top: 58px;
      width: 267px;
      height: 515px;
      background: #fff;
      display: flex;
      flex-direction: column;
      border-radius 0 0 50px 50px
      .box-body
        flex none
        height 448px
        border: 1px solid #dcdcdc;
        box-sizing border-box
        overflow hidden
        transform rotate(0)
        &.hideCover
          scroll()
          height 448px
        .cover-wrapper
          position relative
          height 446px
          overflow hidden
          &.isSlide
            transition all 0.3s ease
          &.useBgImg
            bgCover()
            background-color #fff !important
          &.useBgColor
            background-image none !important
          .cover-title
            position absolute
            left 20px
            right 20px
            max-height 260px
            overflow hidden
            word-break break-all
            &.top
              top 40px
            &.center
              top 50%
              transform translateY(-50%)
            &.bottom
              bottom 120px
          .cover-btn
            position absolute
            bottom 40px
            left 20px
            right 20px
            height 40px
            line-height 40px
            border-radius 6px
            text-align center
            cursor pointer
          .cover-slide
            position absolute
            bottom 0
            left 0
            right 0
            height 80px
            display flex
            flex-direction column
            align-items center
            justify-content center
            .slide-text
              color #fff
              cursor pointer
              margin-bottom 10px
            .slide-icon
              width 16px
              height 16px
              cursor pointer
              background url('~assets/img/survey2.0/message_ic_up_pass@2x.png') no-repeat 0 0 / 100%
        .survey-wrapper
          position relative
          height 446px
          box-sizing border-box
          &.useBgImg
            bgCover()
            background-color #fff !important
          &.useBgColor
            background-image none !important
          &.showBg
            padding 10px 10px 0
          .survey-page-bg
            position absolute
            left 10px
            right 10px
            top 10px
            bottom 0
            background #fff
          .survey-page
            position relative
            z-index 1
            padding 20px 15px
            scroll()
            box-sizing border-box
            .survey-header
              margin -20px -15px 20px
              .header-text
                padding 10px 15px
                line-height 1.5
                font-size 14px
              .header-img
                width 100%
            .survey-cover
              margin-bottom 20px
              word-break break-all
            .survey-accessText
              margin-bottom 20px
              font-size 14px
              word-break break-all
            .survey-question
              .question-item
                margin-bottom 30px
                .qa-title
                  display flex
                  .title-ordinal
                    flex none
                    margin-right 5px
                    line-height 1.5
                  .title-content
                    flex 1
                    line-height 1.5
                    >>> .ordinal
                      color #333 !important
                      margin-right 5px
                    >>> img, >>> iframe, >>> video
                      max-width 100% !important
            .survey-btn-list
              display flex
              height 34px
              .btn-item
                flex 1
                border-radius 4px
                box-sizing border-box
                line-height 34px
                text-align center
                cursor pointer
                &.prev
                  margin-right 5px
                  border 1px solid rgb(38, 114, 255)
                  background #fff
                  color rgb(38, 114, 255)
                &.next
                  background rgb(38, 114, 255)
                  color #fff
                  border 1px solid rgb(38, 114, 255)
      .box-home
        position relative
        flex 1
        .home-icon
          position absolute
          left 50%
          top 50%
          transform translate(-50%, -50%)
          display block
          width 38px
          height 38px
          border-radius 50%
          background #fff
          box-shadow 0 0 10px 1px rgba(0,0,0,0.05)
          border: 1px solid #dcdcdc;
    .cover-page-toggle
      position absolute
      right -22px
      bottom 82px
      width 24px
      display flex
      flex-direction column
      .toggle-item
        width 24px
        height 24px
        background-color #fff
        cursor pointer
        &:first-child
          margin-bottom 10px
        &.arrow-top
          background-position -336px 0
          &.active
            background-position -144px -48px
        &.arrow-down
          background-position -312px 0
          &.active
            background-position -120px -48px
</style>
